import type { HttpError, HttpResponse } from "./type";
import NProgress from "../npprogress";
import { ElMessage } from "element-plus";
import { debounce, isFunction } from "lodash-unified";
import { senselessRefresh } from "./axiosRefresh";

const errorMap = {};

const messageDebounced = debounce(
  (msg) => {
    if (msg) {
      ElMessage({
        message: msg,
        type: "error",
        duration: 2 * 1000,
      });
    }
  },
  1500,
  { leading: true, trailing: false }
);

const errorTips = (axiosError: HttpError) => {
  const errorRes: HttpResponse = axiosError.response;
  const status = errorRes?.status ?? 500;
  const errorMsg =
    (axiosError.response?.data as BaseResType)?.msg ||
    axiosError.message ||
    "未知错误";
  const errorTipKey = `${status}_${errorMsg?.slice(0, 200)}`;
  // console.log("fn==>", messageDebounced(errMessage), "map==>", errorMap);
  if (errorMap[errorTipKey] && isFunction(errorMap[errorTipKey])) {
    errorMap[errorTipKey](errorMsg);
    return;
  }
  errorMap[errorTipKey] = messageDebounced;
  errorMap[errorTipKey](errorMsg);
};

export function checkStatus(axiosError: HttpError): Promise<any> {
  const errorRes: HttpResponse = axiosError.response;
  const status = errorRes?.status ?? 500;

  switch (status) {
    case 400:
      // console.log(errorRes.data, 56, useRoute());
      if (errorRes.data.msg == "sso用户未登录") {
        location.href = "/kg-web/sso/login";
      }
      break;
    case 401:
      // 无感刷新 token
      return senselessRefresh(axiosError, errorTips);
    // break;
    // 请求未授权
    case 403:
      break;
    // 404请求不存在
    case 404:
      break;
    case 500:
      break;
    case 501:
      break;
    case 502:
      break;
    case 503:
      break;
    case 504:
      break;
    default:
      break;
  }

  errorTips(axiosError);
  NProgress.done();

  return Promise.reject(axiosError);
}
